import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import '../css/app.css';

class Hello extends React.Component{
  constructor() {
    super();
    this.state = {
      title:'还未改变',
      loading: false,
      list: []
    }
  }
  static defaultProps = {
    title: '222222'
  }
  //初始值的时候，可以直接定义state，或者在constructor中使用this.state
  //如果同是都定义了state，则最后结果是constructor为准
  // state = {
  //     title: '变变'
  //   }
  componentDidMount() {
    var number = 5;
    setTimeout(function() {
      this.setState({
        num: 5,
        loading: true,
        list: ['Beijing', 'Shanghai', 'Tianjin']
      });

      var timer = setInterval(function(){

        if(this.state.num === 0){
          clearInterval(timer);
          return;
        };

        this.setState({
          num:--number
        });
      }.bind(this),1000);

    }.bind(this),2000);
    console.log(this)
  }
  handleClick(e) {
    console.log(e.target.innerText); //e.target为当前点击的元素
    if(this !== null)
    this._ul.className = 'rotate';
  }
  //使用箭头函数定义，在调用的时候就不需要bind（this）
  alertClick = (e) => {
    this.setState({
      title: '已改变'
    })
  }
  render() {
    return (<div>
        <ul ref={(c) => this._ul = c}>
          {
            this.state.loading === true ? this.state.num === 0 ? this.state.list.map((val,i)=><li className="list" key={i}>hello, {val}</li>) : <li className="time">{this.state.num}</li> : <li className="time" >loading...</li>
          }

        </ul>
        <a href="javascript:;" onClick={this.handleClick.bind(this)}>点击移动</a>
        <div>{this.props.title}</div>
        <div onClick={this.alertClick}>{this.state.title}</div>
      </div>
      )
  }
}
//设置默认属性，只能放在外边或者在类里面使用static
Hello.defaultProps = {
      title: '测试'
    }
ReactDOM.render(
  <Hello />, 
  document.getElementById('root')
);

//redux实现点击加减
const Counter = ({ value, onIncrement, onDecrement }) => (<div className="num">
  <h1>{value}</h1>
  <button type="button" onClick={onIncrement}>+</button>
  <button type="button" onClick={onDecrement}>-</button>
  </div>
);

const reducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT': return state + 1;
    case 'DECREMENT': return state - 1;
    default: return state;
  }
};

const store = createStore(reducer);

const render = () => {
  ReactDOM.render(
    <Counter value={store.getState()} onIncrement={() => store.dispatch({type: 'INCREMENT'})} onDecrement={() => store.dispatch({type: 'DECREMENT'})}
    />,
    document.getElementById('content')
  );
};

render();
store.subscribe(render);